<template>
  <div style="text-align: center">
    <el-button @click="dialogVisible = true" style="float: right">选择</el-button>
    <el-dialog v-model="dialogVisible" width="30%" style="min-width: 600px;min-height: 500px" :top="'10px'">
      <div style="margin-bottom: 10px;display: flex">
        <search-kind-component v-model="searchKinds" style="display: inline-block;margin-right: 10px;width: 100px"/>
        <el-input v-model="keyword" style="width: 350px;margin-right: 10px;font-size: 16px" :placeholder="sk_index===1?'请输入正确的邮箱':'请输入作者名字，格式：名@姓'"/>
        <el-button @click="getAuthors(keyword)">搜索</el-button>
      </div>
      <hr>
      <author-search-result-component v-model="authors"/>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="canal">取消</el-button>
        <el-button type="primary" @click="add">添加</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {provide, ref, defineModel} from 'vue'
import {getPagedAuthorsApi, getById} from '@/apis/author.js'
import {ElMessage} from "element-plus";
import AuthorSearchResultComponent from "./AuthorSearchResultComponent.vue";
import SearchKindComponent from "../common/SearchKindComponent.vue";

const dialogVisible = ref(false)
const keyword = ref('')
const authors = ref([]) // 查询结果集合
const index = ref(-1)
provide('index', index)

const sk_index = ref(0)
const searchKinds = ref(['姓名', '邮箱'])
provide('sk_index', sk_index)

// 查询作者
const getAuthors = (skw) => {
  skw = skw.trim() // 查询关键词
  if (!skw) {
    ElMessage.error('请输入查询关键词')
  } else if (sk_index.value === 0 || sk_index.value === 1) {
    getPagedAuthorsApi(1, 20, sk_index.value + 1, skw).then(resp => {
      if (resp.data.code === 200) {
        index.value = -1 // 取消选中状态
        authors.value = resp.data.data.records
        console.log(authors.value)
      } else {
        ElMessage.error(resp.data.msg)
      }
    })
  } else {
    ElMessage.error('查询类别有误')
  }
}

// 已选作者集合
const documentAuthor = defineModel()

const canal = () => {
  index.value = -1
  keyword.value = ''
  authors.value = []
  dialogVisible.value = false
}

const add = () => {
  const i = index.value
  if (i >= 0 && i < authors.value.length) {
    const author = authors.value[i]
    const aid = author.id //选中的作者的id
    if (aid) {
      getById(aid).then(resp => {
        if (resp.data.code === 200) {
          const author = resp.data.data
          // 若作者存在
          if (author?.id) {
            documentAuthor.value = author
            ElMessage.success(`添加作者[${author.firstName}@${author.lastName}]成功`)
            canal() // 退出对话框
          } else {
            ElMessage.error('作者不存在');
          }
        } else {
          ElMessage.error(resp.data.msg)
        }
      })
    }
  } else {
    ElMessage.error('请选择作者')
  }
}


</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}


</style>
